import {StyleSheet, Text, TouchableOpacity, View, Image, ImageBackground} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import {StatusBar} from "expo-status-bar";
import {router, useLocalSearchParams} from "expo-router";
import {Toast, Flex} from "@ant-design/react-native";
import { useFocusEffect } from '@react-navigation/native';

import {
  useGetWorksMutation,
  useQueryTaskStatusMutation,
  useDeleteBatchMutation,
  useGetGenListQuery
} from "@/store/api/videoAndPictrue/videoAndPictrueApi";

type Props = {}

const worksAll = (props: Props) => {
  const [listParams, setListParams] = useState<any>({
    pageNo: 1,
    pageSize: 20,
    type: 0,
  })
  const [list,setList] = useState<any>([])
  const [worksType,setWorksType] = useState<any>('')
  const [deleteOpen,setDeleteOpen] = useState(false)
  const [isBatch,setIsBatch] = useState(false)

  const timer:any = useRef(null)

  const {data:listDataRef,isSuccess:listSuccess,refetch:listRefetch} = useGetGenListQuery(listParams)
  
  const [genWorksFun] = useGetWorksMutation()
  const [queryTaskStatusFun] = useQueryTaskStatusMutation()
  const [deleteBatchFun] = useDeleteBatchMutation()

  const {type} = useLocalSearchParams()
  
  useEffect(() => {
    setListParams({
      ...listParams,
      type: type
    })

    setWorksType(type)

    listRefetch();
  }, [type]);

  useEffect(() => {
    if(listDataRef?.code === 200){
      const arr = listDataRef?.result?.records || []

      const updatedArr = arr.map((item: any) => {
        let time: any = new Date().getTime() - new Date(item.createTime).getTime();
        return {
          ...item,
          checked: false,
          daysDiff: Math.floor(time / (1000 * 60 * 60 * 24))
        };
      });
      setList(updatedArr)

      console.log(listDataRef, list,'listDataRef===>');
    }
  }, [listDataRef, listSuccess]);

  useEffect(() => {
    if (list.length > 0) {
      filterListStatus();
    }
  }, [list]);

  useFocusEffect(
    React.useCallback(() => {
      return () => {
        clearInterval(timer.current)
      };
    }, [])
  );

  const filterListStatus = () => {
    let ids = []

    for(let i in list){
      for(let j in list[i].detailList){
        if(list[i].detailList[j].taskStatus == 'submitted' || list[i].detailList[j].taskStatus == 'processing'){
          ids.push(list[i].id)
          break;
        }
      }
    }

    if(ids.length > 0){
      clearInterval(timer.current)

      timer.current = setInterval(() => {
        handleQueryTaskStatus(ids.join())
      }, 10000)
    }
  }

  //获取作品生成状态
  const handleQueryTaskStatus = (id:any) => {
    queryTaskStatusFun({ids: id}).then(res => {
      let arr = []
      let arr1 = JSON.parse(JSON.stringify(list))

      for(let i in res.data.result){
        let list = res.data.result[i].detailList?.filter((val:any) => val.taskStatus == 'submitted' || val.taskStatus == 'processing')

        if(list?.length > 0) arr.push(res.data.result[i])

        for(let j in arr1){
          if(res.data.result[i].id == arr1[j].id){
            arr1[j].detailList = res.data.result[i].detailList
          }
        }
      }

      setList(arr1)

      if(arr.length == 0){
        clearInterval(timer.current)
      }
    })
  }

  //选中
  const handleCheckItme = (index:any) => {
    let arr = JSON.parse(JSON.stringify(list))
    arr[index].checked = !arr[index].checked
    setList(arr)
  }

  //打开删除弹窗
  const handleDeleteOpen = () => {
    let arr = list.filter((val:any) => val.checked)

    if(arr.length == 0){
      Toast.info(`请选中${worksType == 0 ? '视频' : '图片'}`)
      return
    }

    setDeleteOpen(true)
  }

  //删除
  const handleDelete = () => {
    let arr = list.filter((val:any) => val.checked).map((val:any) => val.id)

    deleteBatchFun({ids: arr.join()}).then(res => {
      listRefetch();
      setIsBatch(false)
      Toast.info('删除成功')
    })
  }

  //通过URL下载视频或图片
  const handleDownload = () => {
    let arr = list.filter((val:any) => val.checked)

    if(arr.length == 0){
      Toast.info(`请选中${worksType == 0 ? '视频' : '图片'}`)
      return
    }
    arr.forEach((item:any, index:any) => {
      item.detailList.forEach((childrenItem:any, childrenIndex:any) => {
        if(childrenItem.viewUrl || childrenItem.ownViewUrl){
          let xhr = new XMLHttpRequest();
          xhr.open("GET", childrenItem.viewUrl || childrenItem.ownViewUrl, true);
          xhr.responseType = "blob";
          xhr.onload = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
              let a = document.createElement("a");
              a.href = window.URL.createObjectURL(new Blob([xhr.response], { type: item.type == 1 ? 'image/png' : 'video/mp4' }));
              a.download = item.id;
              document.body.appendChild(a);
              a.click();
              a.remove();
            }
          };
          xhr.send();
        }
      })
    })

    setIsBatch(false)
    listRefetch();
  }

  return (
    <View style={{flex: 1}}>
      <StatusBar style='light'></StatusBar>
      <ImageBackground 
        source={require('@/assets/images/public/black_bg.png')}
        style={{flex: 1, width: '100%'}}
      >
        <PageScrollView
          isTransparentTab
          themedStyle={{backgroundColor: 'transparent'}}
          pageTab={
            <PageTabBar
              style={{marginVertical: 10}}
              titleStyle={{color: '#FFF'}}
              title={worksType == 0 ? '所有视频' : '所有图片'}
              right={
                <View>
                  {
                    !isBatch ?
                    <TouchableOpacity style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} onPress={() => setIsBatch(true)}>
                      <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: '#FFF', marginRight: 3}}>&#xe797;</Text>
                      <Text style={{color: '#FFF'}}>批量操作</Text>
                    </TouchableOpacity>
                    : null
                  }
                </View>
              }
              left={
                <Flex style={{paddingLeft: 16}}>
                  <TouchableOpacity onPress={() => router.back()}>
                    <Text style={{fontFamily: 'FcIconFont', fontSize: 25, color: '#FFF', marginRight: 3}}>&#xe61a;</Text>
                  </TouchableOpacity>
                </Flex>
              }
            />
          }
          pageBottom={
            <View>
              {
                isBatch ? 
                <Flex justify='between' style={{height: 56, backgroundColor: '#1B1D2A', paddingHorizontal: 10}}>
                  <FcButton
                    onClick={() => handleDeleteOpen()}
                    type='BjJB'
                    colors={['#26293D', '#26293D']}
                    style={{width: '48%', height: 40, justifyContent: 'center'}}
                    itemStyle={{borderRadius: 8, fontSize: 15}}
                    textName='删除'
                  />
                  <FcButton
                    onClick={() => handleDownload()}
                    type='BjJB'
                    colors={['#6989FF', '#C65EFD']}
                    style={{width: '48%', height: 40, justifyContent: 'center'}}
                    itemStyle={{borderRadius: 8, fontSize: 15}}
                    textName={worksType == 0 ? '下载视频' : '下载图片'}
                  />
                </Flex>
              : null
              }
            </View>
          }
        >
          <View>
            <Flex wrap='wrap' justify='between'>
              {
                list?.map((item:any, index:any) => (
                  <TouchableOpacity key={index} style={styles.list_item} onPress={() => router.push(`/videoAndPictrue/works?id=${item.id}`)}>
                    {
                      item?.detailList[0].taskStatus == 'submitted' || item?.detailList[0].taskStatus == 'processing' ? 
                      <View style={{position: 'relative', flex: 1}}>
                        <Flex direction='column' justify='center' style={{height: '80%'}}>
                          <Image style={{width: 80, height: 65}} resizeMode={'cover'} source={require('@/assets/images/loading.gif')}></Image>
                          <Text style={{fontSize: 12, color: '#6989FF'}}>视频生成中</Text>
                        </Flex>
                        {
                          isBatch ? 
                          <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active, styles.check]} onPress={() => {handleCheckItme(index)}}>
                            {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                          </TouchableOpacity>
                          : null
                        }
                      </View>
                      :
                      <View style={{flex: 1}}>
                        <Image style={{width: '100%', height: '100%', borderRadius: 8}} resizeMode={item.aspectRatio == '16:9' ? 'cover' : 'contain'} source={{uri: item.type == 0 ? item?.detailList[0].thumbnail : item?.detailList[0].viewUrl}}></Image>
                        <Text style={{fontSize: 12, color: '#FFF', position: 'absolute', bottom: 0, textAlign: 'center', width: '100%'}}>{item.type == 0 ? '视频' : '图片'}于<Text style={{fontSize: 12, color: '#FA5151'}}>{ 30 - item.daysDiff}</Text>天后删除</Text>
                        <Flex style={{position: 'absolute', top: 5, left: 5}}>
                          <Text style={styles.list_item_info}>共{item.detailList.length}{item.type == 0 ? '条' : '张'}</Text>
                          {
                            item.type == 0 ?
                            <Text style={[styles.list_item_info, {marginLeft: 5}]}>{item.duration || 0}S</Text>
                            : null
                          }
                        </Flex>

                        {
                          isBatch ? 
                          <TouchableOpacity style={[styles.select_icon, item.checked && styles.select_active, styles.check]} onPress={() => {handleCheckItme(index)}}>
                            {item.checked && <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                          </TouchableOpacity>
                          : null
                        }
                      </View>
                    }
                  </TouchableOpacity>
                ))
              }
            </Flex>
          </View>

          {/* 删除弹窗 */}
          <FcModal
            isOpen={deleteOpen}
            transparent
            closeShow={false}
            animationType='fade'
            onFcModalClose={() => setDeleteOpen(false)}
            style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
            titleText={'确认要删除吗？'}
            titleBottomBorderWidth={0}
            footer={[
              {
                text: '取消',
                onPress: () => setDeleteOpen(false),
                style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
              },
              {
                text: '确认',
                onPress: () => handleDelete(),
                style: { color: '#2856FF',fontSize: 17 },
              },
            ]}
          >
            <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前视频将被删除哦~</Text>
          </FcModal>
        </PageScrollView>
      </ImageBackground>
    </View>
  )
}

export default worksAll

const styles = StyleSheet.create({
  list_item: {
    width: '48.6%',
    height: 120,
    borderRadius: 8,
    backgroundColor: '#000000',
    marginBottom: 10,
    position: 'relative',
  },
  list_item_info: {
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    paddingVertical: 3,
    paddingHorizontal: 5,
    color: '#FFF',
    fontSize: 12,
    borderRadius: 4,
  },
  select_icon: {
    width: 17,
    height: 17,
    borderRadius: '50%',
    borderWidth: 1,
    borderColor: '#FFF',
  },
  select_active: {
    borderColor: '#2856FF',
    backgroundColor: '#2856FF',
    flexDirection: 'row',
    alignItems: "center",
    justifyContent: "center"
  },
  check: {
    position: 'absolute',
    top: 5,
    right: 5,
  }
})